package com.sgb.kjwl.view.ui.activity.house;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.sdk.mobile.manager.login.NoDoubleClickListener;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentLeaseHallMap2Binding;
import com.sgb.kjwl.di.machine.DaggerMachineFragComponent;
import com.sgb.kjwl.di.machine.MachineFragModule;
import com.sgb.kjwl.model.LocationAddressInfo;
import com.sgb.kjwl.model.entity.lease.DictEntity4;
import com.sgb.kjwl.model.entity.lease.LeaseMapEntity;
import com.sgb.kjwl.model.entity.request.LeaseHallMapFilterJson;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.activity.lease.ZulinGaodeSearchActivity;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.view.widget.MapInfoDialog5;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.house.LeaseHallMapFragModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 地图查找Fragment
 * 参照 https://blog.csdn.net/qq_31622345/article/details/111631616
 */
@Deprecated
public class LeaseHallMapFragment2 extends AppLazyFragment implements
        AMap.OnMarkerClickListener,
        LocationSource,
        AMapLocationListener,
        GeocodeSearch.OnGeocodeSearchListener,
        AMap.OnCameraChangeListener {


    @Inject
    LeaseHallMapFragModel viewModel;
    private FragmentLeaseHallMap2Binding binding;
    private List<String> cityList = new ArrayList<>();
    private ThreeLevelAreaWindow mAddressPop;

    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;//省市区
    private List<DictEntity3> typeDictEntityList;//分类
    private DictWindow5 classifyWindow;//分类
    private DictWindow5 brandlWindow5;//类型
    private List<DictEntity3> brandDictEntityList;//类型
    private String categoryParentId = "";

    private String provinceName = "";
    private String cityName = "";
    private List<LeaseMapEntity> bundles = new ArrayList<>();
    private LeaseHallMapFilterJson filterJson = new LeaseHallMapFilterJson();
    private Bundle savedInstanceState;


    private boolean isModifyAddr = false;
    private Bundle bundle;
    private AMap mAMap;
    private Marker mGPSMarker;             //定位位置显示
    private AMapLocation location;
    private LocationSource.OnLocationChangedListener mListener;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    //你编码对象
    private GeocodeSearch geocoderSearch;

    private MarkerOptions markOptions;
    private LatLng latLng;
    private String addressName;
    private String type = "1";


    private boolean isHaveData = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        this.savedInstanceState = savedInstanceState;
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMachineFragComponent.builder()
                .appComponent(appComponent)
                .machineFragModule(new MachineFragModule(this))
                .build()
                .inject(this);
    }

    public static LeaseHallMapFragment2 newInstance(String type) {
        LeaseHallMapFragment2 fragment = new LeaseHallMapFragment2();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static LeaseHallMapFragment2 newInstance2(String type, String title, String text, double lat, double lon) {
        LeaseHallMapFragment2 fragment = new LeaseHallMapFragment2();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        bundle.putString("title", title);
        bundle.putString("text", text);
        bundle.putDouble("lat", lat);
        bundle.putDouble("lon", lon);
        fragment.setArguments(bundle);
        return fragment;
    }


    private void getArgument() {
        bundle = getArguments();
        type = bundle.getString("type");
        String text = bundle.getString("text");
        String title = bundle.getString("title");
        filterJson.setType(type);
        if (!TextUtils.isEmpty(text)) {
            if (title.equals("图选")) {
                isModifyAddr = true;
                binding.mapAddress.llAddrDetail.setVisibility(View.VISIBLE);
                binding.mapAddress.tvAddr.setText(addressName);
                isHaveData = false;
            } else {
                isHaveData = true;
                addressName = bundle.getString("text");
                double lat = bundle.getDouble("lat");
                double lon = bundle.getDouble("lon");
                latLng = new LatLng(lat, lon);
                filterJson.setLatitude(latLng.latitude);
                filterJson.setLongitude(latLng.longitude);
                getAllList();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LocationAddressInfo event) {
        if (event != null) {
            if (event.getTitle().equals("图选")) {
                isModifyAddr = true;
                binding.mapAddress.llAddrDetail.setVisibility(View.VISIBLE);
                binding.mapAddress.tvAddr.setText(addressName);
                isHaveData = false;
            }else {
                addressName = event.getText();
                binding.mapAddress.tvAddr.setText(addressName);
                latLng = new LatLng(event.getLat(), event.getLon());
                setMarket(latLng, "", addressName);
                mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
                filterJson.setLatitude(latLng.latitude);
                filterJson.setLongitude(latLng.longitude);
                getAllList();
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(DictEntity4 event) {
        if (event != null) {
            type = event.getKey();
            filterJson.setType(type);
            if(!isModifyAddr){
                getAllList();
            }
        }
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_lease_hall_map2, container, false);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return binding.getRoot();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        checkDismiss(0);
    }

    @Override
    protected void initView() {
        getArgument();
        requestPermission();
        binding.classifyLayout.setOnClickListener(this);
        binding.typeLayout.setOnClickListener(this);
        binding.areaLayout.setOnClickListener(this);
        binding.tvModify.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {//修改地址
                if (isModifyAddr) {
                    return;
                }
                isModifyAddr = true;
                binding.mapAddress.llAddrDetail.setVisibility(View.VISIBLE);
                binding.mapAddress.tvAddr.setText(addressName);

                addMarkInfoWindow2(bundles);
                mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
                getAddress(latLng);
            }
        });
        //跳修改地址列表
        binding.mapAddress.tvAddr.setOnClickListener(v -> {
            isModifyAddr = false;
            binding.mapAddress.llAddrDetail.setVisibility(View.GONE);
            ZulinGaodeSearchActivity.start(getActivity(), true, addressName);
        });
        binding.mapAddress.btQueding.setOnClickListener(this);
        initFilterView();
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //设置定位权限
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //        Log.i(TAG,"权限申请成功！");
                    if (!isHaveData) {
                        mLocationClient.startLocation();//开启定位
                    }
                } else {
                    LatLng lat = new LatLng(39.903114318847656, 116.39775848388672);
                    mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lat, 16));
                    addMarker2(latLng, "北京市东城区前门东大街11号");
                    if (!isHaveData) {
                       // MToast.showToast(getActivity(), "无法获取当前位置,请输入使用地点");
                    }
                }
                return;
        }
    }

    @Override
    protected void onLazyLoad() {
        if ("3".equals(type)) {
            binding.tvClassify.setText("车型");
            binding.tvType.setText("品牌");
        } else if ("6".equals(type)) {//工厂没有类型,需隐藏
            binding.typeLayout.setVisibility(View.GONE);
        }
        provinceName = viewModel.getAreaNameModel();
        filterJson.setProvinceNo(viewModel.getAreaCodeModel());
        viewModel.getFilterTypeModel(type);
        initMap(savedInstanceState);
    }


    private void initFilterView() {
        //分类选择
        classifyWindow = new DictWindow5(getActivity());
        classifyWindow.setFocusable(false);
        classifyWindow.setOutsideTouchable(false);
        classifyWindow.setOnCallBack(dictEntity -> {
            updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 2, dictEntity.getName());
            if (!"3".equals(type)) {
                //重置类型
                if (brandDictEntityList != null && brandDictEntityList.size() > 0) {
                    brandlWindow5.setCheckDefaultById(brandDictEntityList.get(0).getId());
                    filterJson.setSecondCategory(brandDictEntityList.get(0).getId());
                }
            }

            //设置筛选结果
            categoryParentId = dictEntity.getId();
            filterJson.setFirstCategory(dictEntity.getId());
            getAllList();
        });
        classifyWindow.setOnCloseBack(() -> {
            if ("分类".equals(binding.tvClassify.getText()) || "车型".equals(binding.tvClassify.getText())) {
                updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 0, null);
            } else {
                updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 2, null);
            }
        });

        //类型选择
        brandlWindow5 = new DictWindow5(getActivity());
        brandlWindow5.setFocusable(false);
        brandlWindow5.setOutsideTouchable(false);
        brandlWindow5.setOnCallBack(dictEntity -> {
            updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, dictEntity.getName());
            filterJson.setSecondCategory(dictEntity.getId());
            getAllList();
        });
        brandlWindow5.setOnCloseBack(() -> {
            if ("类型".equals(binding.tvType.getText()) || "品牌".equals(binding.tvType.getText())) {
                updateChooseTextStatus(binding.typeLayout, binding.tvType, 0, null);
            } else {
                updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, null);
            }
        });

        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(binding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setProvinceSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setAreaMore();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnResultClick((key1, key2, key3) -> {
            try {
                List<BaseAreaEntity> listKey1 = (List<BaseAreaEntity>) key1;
                List<BaseAreaEntity> listKey2 = (List<BaseAreaEntity>) key2;
                List<BaseAreaEntity> listKey3 = (List<BaseAreaEntity>) key3;
                filterJson.setAreaNos(getCityList(listKey3)); //获取区多选列表
                if (listKey2 != null && listKey2.size() > 0) {
                    cityName = listKey2.get(0).getName();
                    filterJson.setCityNo(listKey2.get(0).getNo());
                } else {
                    filterJson.setCityNo("");
                }
                filterJson.setProvinceNo(listKey1.get(0).getNo());
                provinceName = listKey1.get(0).getName();
            } catch (Exception exception) {
            }

            getAllList();
            if (!TextUtils.isEmpty(cityName) && "不限".equals(cityName)) {
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, cityName);
            } else {
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, provinceName);
            }

        });
        mAddressPop.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? 0 : 2, null);
        });

    }

    private List<String> getCityList(List<BaseAreaEntity> list) {
        cityList = new ArrayList<>();
        for (BaseAreaEntity entity : list) {
            if (!TextUtils.isEmpty(entity.getNo())) {
                cityList.add(entity.getNo());
            }
        }
        return cityList;
    }


    private void getAllList() {
        viewModel.getLeaseMapSearch(filterJson, false);
    }


    //初始化地图
    private void initMap(Bundle savedInstanceState) {
        binding.mapView.onCreate(savedInstanceState);
        geocoderSearch = new GeocodeSearch(getActivity());
        mAMap = binding.mapView.getMap();
        mAMap.setOnMarkerClickListener(this);
        mAMap.setLocationSource(this);
        mAMap.setOnCameraChangeListener(this);//设置地图拖动监听
        geocoderSearch.setOnGeocodeSearchListener(this);


        //导航箭头定位的小图标，这里自定义一张图片
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        myLocationStyle.anchor(0.5f, 0.7f);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色  这样圆圈就没有了，看不到了
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        mAMap.setMyLocationStyle(myLocationStyle);
        mAMap.moveCamera(CameraUpdateFactory.zoomTo(16)); //缩放比例


        //设置amap的属性
        UiSettings settings = mAMap.getUiSettings();
        settings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        settings.setZoomControlsEnabled(false);//隐藏放大缩小

        //isHaveData 为true 说明有经纬度传过来，所以不需要在开启定位
        if (isHaveData) {
            mAMap.setMyLocationEnabled(false);//关闭定位
        } else {
            mAMap.setMyLocationEnabled(true);//开启定位
        }
    }


    //设置一级分类数据
    public void showTypePopWindow(List<DictEntity3> data) {
        this.typeDictEntityList = data;
        if (data == null) {
            data = new ArrayList<>();
        }
        categoryParentId = filterJson.getFirstCategory();
        if (TextUtils.isEmpty(categoryParentId)) {
            categoryParentId = data.get(0).getId();
        }
        classifyWindow.setData(data);
        classifyWindow.setCheckDefaultById(categoryParentId);
        filterJson.setFirstCategory(categoryParentId);
    }

    //设置二级分类数据
    public void showBrandPopWindow(List<DictEntity3> data) {
        this.brandDictEntityList = data;
        if (data == null) {
            data = new ArrayList<>();
        }
        String defaultId = filterJson.getSecondCategory();
        if (TextUtils.isEmpty(defaultId)) {
            defaultId = "";
        }
        brandlWindow5.setData(data);
        brandlWindow5.setCheckDefaultById(defaultId);
        filterJson.setSecondCategory(defaultId);
    }

    public void showMapMark(List<LeaseMapEntity> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        addMarkInfoWindow(list);
    }

    private MarkerOptions markerOption1;

    private void addMarkInfoWindow(List<LeaseMapEntity> datas) {
        try {
            mAMap.clear();
            bundles.clear();
            if (datas.size() > 0) {
                for (int i = 0; i < datas.size(); i++) {
                    LeaseMapEntity entity = datas.get(i);
                    if (checkItude(entity.getLongitude(), entity.getLatitude())) {
                        LatLng latLng = new LatLng(Double.parseDouble(entity.getLatitude()), Double.parseDouble(entity.getLongitude()));
                        int icon = getIcon(entity.getType());
                        bundles.add(entity);
                        binding.bottomIcon.setImageResource(icon);
                        markerOption1 = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(icon))
                                .position(latLng)
                                .period(i)
                                .infoWindowEnable(false)
                                .draggable(true);
                        mAMap.addMarker(markerOption1);
                    }
                }
                if (!isModifyAddr) {//不修改地点时添加marker
                    mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
                    addMarker3(latLng);
                }
                if (!isHaveData && isModifyAddr) {
                    setMarket(latLng, "", addressName);
                }
            } else {
                Toast.makeText(getActivity(), "没有数据", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addMarkInfoWindow2(List<LeaseMapEntity> datas) {
        try {
            mAMap.clear();
            for (int i = 0; i < datas.size(); i++) {
                LeaseMapEntity entity = datas.get(i);
                if (checkItude(entity.getLongitude(), entity.getLatitude())) {
                    LatLng latLng = new LatLng(Double.parseDouble(entity.getLatitude()), Double.parseDouble(entity.getLongitude()));
                    int icon = getIcon(entity.getType());
                    binding.bottomIcon.setImageResource(icon);
                    markerOption1 = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(icon))
                            .position(latLng)
                            .infoWindowEnable(false)
                            .draggable(true);

                    mAMap.addMarker(markerOption1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int getIcon(String type) {
        int icon = R.mipmap.ic_map_overlay_machine;
        if ("1".equals(type)) {
            icon = R.mipmap.ic_map_overlay_machine;
        } else if ("2".equals(type)) {
            icon = R.mipmap.ic_map_overlay_device;
        } else if ("3".equals(type)) {
            icon = R.mipmap.ic_map_overlay_car;
        } else if ("4".equals(type)) {
            icon = R.mipmap.ic_map_overlay_house;
        } else if ("5".equals(type)) {
            icon = R.mipmap.ic_map_overlay_land;
        } else if ("6".equals(type)) {
            icon = R.mipmap.ic_map_overlay_factory;
        } else if ("7".equals(type)) {
            icon = R.mipmap.ic_map_overlay_farm;
        }
        return icon;
    }

    public void showAddressDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data, String provinceNo) {
        if (data != null && data.size() > 0) {
            addressEntityList = data;
            filterJson.setProvinceNo(provinceNo);
            mAddressPop.setData(data, true, provinceNo);
        }
    }

    @Override
    public void onClick(View v) {
        checkDismiss(v.getId());
        switch (v.getId()) {
            case R.id.classify_layout://分类
                if ("分类".equals(binding.tvClassify.getText()) || "车型".equals(binding.tvClassify.getText())) {
                    updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, -1, null);
                } else {
                    updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 1, null);
                }
                classifyWindow.setCheckDefaultById(filterJson.getFirstCategory());
                classifyWindow.showPopwindow(binding.classifyLayout);
                if (typeDictEntityList == null) {
                    viewModel.getFilterTypeModel(type);
                }
                break;
            case R.id.type_layout://类型
                if ("类型".equals(binding.tvType.getText()) || "品牌".equals(binding.tvType.getText())) {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, -1, null);
                } else {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 1, null);
                }
                brandlWindow5.setCheckDefaultById(filterJson.getSecondCategory());
                brandlWindow5.showPopwindow(binding.typeLayout);
                viewModel.getFilterModelModel(type, categoryParentId);
                break;
            case R.id.area_layout://地区
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? -1 : 1, null);
                mAddressPop.showPopwindow(binding.areaLayout);
                if (addressEntityList == null) {
                    viewModel.getCityData();
                }
                break;
            case R.id.bt_queding:
                isModifyAddr = false;
                binding.mapAddress.llAddrDetail.setVisibility(View.GONE);
                filterJson.setLatitude(latLng.latitude);
                filterJson.setLongitude(latLng.longitude);
                getAllList();
                binding.mapAddress.tvAddr.setText(addressName);
                break;

        }
    }

    private void checkDismiss(int rid) {
        if (rid != R.id.classify_layout && classifyWindow != null && classifyWindow.isShowing()) {
            classifyWindow.dismiss();
        }
        if (rid != R.id.type_layout && classifyWindow != null && brandlWindow5.isShowing()) {
            brandlWindow5.dismiss();
        }
        if (rid != R.id.area_layout && classifyWindow != null && mAddressPop.isShowing()) {
            mAddressPop.dismiss();
        }
    }

    //更新选项颜色
    private void updateChooseTextStatus(View view, TextView textView, int value, String name) {
        if (!TextUtils.isEmpty(name)) {
            textView.setText(name);
        }
        if (value == 0) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
        } else if (value == -1) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_up_arrow_n, R.color.color_333333);
        } else if (value == 1) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_up_red, R.color.color_main);
        } else if (value == 2) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_down_red, R.color.color_main);
        }
    }

    //设置背景色和图标
    private void setTextViewBg(View view, TextView textView, int bg, int img, int textColor) {
        view.setBackgroundResource(bg);
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }


    /**
     * 经纬度校验(只校验正数 0-90.000000 0-180.000000 范围内)
     * 经度longitude: (?:[0-9]|[1-9][0-9]|1[0-7][0-9]|180)\\.([0-9]{6})
     * 纬度latitude：  (?:[0-9]|[1-8][0-9]|90)\\.([0-9]{6})
     *
     * @return
     */
    public static boolean checkItude(String longitude, String latitude) {
        if (TextUtils.isEmpty(longitude) || TextUtils.isEmpty(latitude)) {
            return false;
        }

        try {
            //判断经纬度中国境内正确范围
            if (Double.parseDouble(longitude) > 72.8041 && Double.parseDouble(longitude) < 137.8347) {
                return Double.parseDouble(latitude) > 3.5182 && Double.parseDouble(latitude) < 53.8271;
            } else {
                return false;
            }
        } catch (Exception ex) {
            return false;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        location = aMapLocation;
        if (mListener != null && location != null) {
            if (location != null && location.getErrorCode() == 0) {
                mListener.onLocationChanged(location);// 显示系统箭头
                mLocationClient.stopLocation();
                latLng = new LatLng(location.getLatitude(), location.getLongitude());
                filterJson.setLatitude(latLng.latitude);
                filterJson.setLongitude(latLng.longitude);
                getAllList();
            }
        } else {
            //Toast.makeText(getActivity(), "无法获取当前位置,请输入使用地点", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        if(mGPSMarker.isInfoWindowShown()){
            mGPSMarker.hideInfoWindow();
            binding.mapView.invalidate();
        }
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        if (isModifyAddr) {
            latLng = cameraPosition.target;
            getAddress(latLng);
        }
    }

    /**
     * 根据经纬度得到地址
     */
    public void getAddress(final LatLng latLng) {
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if(!isModifyAddr){
            showMarkerView(marker);
        }
        return false;
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        //初始化定位
        mLocationClient = new AMapLocationClient(getActivity());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);

        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000 * 10);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                addressName = result.getRegeocodeAddress().getFormatAddress();// 逆转地里编码不是每次都可以得到对应地图上的opi
                if (isModifyAddr) {
                    binding.mapAddress.tvAddr.setText(addressName);
                    setMarket(latLng, "", addressName);
                    mGPSMarker.showInfoWindow();
                    binding.mapView.invalidate();
                }
            }
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        binding.mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        binding.mapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        binding.mapView.onDestroy();
    }

    private void setMarket(LatLng latLng, String title, String content) {
        if (mGPSMarker != null) {
            mGPSMarker.remove();
        }
        //获取屏幕宽高
        WindowManager wm = getActivity().getWindowManager();
        int width = (wm.getDefaultDisplay().getWidth()) / 2;
        int height = ((wm.getDefaultDisplay().getHeight()) / 2) - 200;
        markOptions = new MarkerOptions();
        markOptions.draggable(false);
        binding.mapView.getMap().setInfoWindowAdapter(new MapInfoWinAdapter(getActivity()));
        markOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_location));
//        markOptions.icon(BitmapDescriptorFactory.fromView(getInfoWindow(content)));
        //   markOptions.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.map_location))).anchor(0.5f, 0.7f);
        //设置一个角标
        mGPSMarker = mAMap.addMarker(markOptions);
        //设置marker在屏幕的像素坐标
        mGPSMarker.setPosition(latLng);
        mGPSMarker.setTitle(title);
        mGPSMarker.setSnippet(content);
        //设置像素坐标
        mGPSMarker.setPositionByPixels(width, height);
        //   if (!TextUtils.isEmpty(content)) {
        mGPSMarker.hideInfoWindow();
        // }
        binding.mapView.invalidate();
    }

    private MarkerOptions markerOption;
    private void addMarker2(LatLng la, String addr) {
        markerOption = new MarkerOptions()
                .position(la)
                .icon(BitmapDescriptorFactory.fromView(getInfoWindow(addr)))
                //  .snippet(addr)
//                .period(1000)
                .draggable(true);
        mAMap.addMarker(markerOption).hideInfoWindow();
    }

    private void addMarker3(LatLng la) {
        markerOption = new MarkerOptions()
                .position(la)
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_location))
                //  .snippet(addr)
                .period(1000)
                .draggable(true);
        mAMap.addMarker(markerOption).hideInfoWindow();
    }

    public View getInfoWindow(String addr) {
        View view = View.inflate(getActivity(), R.layout.marker_info_layout, null);
        TextView tv_addr = view.findViewById(R.id.tv_addr);
        tv_addr.setText(addr);
        return view;
    }

    //展示地图覆盖物
    private void showMarkerView(Marker marker) {
        LeaseMapEntity data = bundles.get(marker.getPeriod());
        if (data != null) {
//            new MapInfoDialog5(getActivity(), null)
//                    .setCallBackListener(entity -> {
//                        if ("7".equals(type)) {
//                            viewModel.getH5Url(Integer.parseInt(type), entity.getNo());
//                        } else {
//                            viewModel.getH5Url(Integer.parseInt(type), entity.getDataId());
//                        }
//                    })
//                    .setData(data);
        }
    }

}
